package com.cisdi.blog.service.impl;

import com.cisdi.blog.dao.TypeRepository;
import com.cisdi.blog.entity.Type;
import com.cisdi.blog.exception.NotFoundException;
import com.cisdi.blog.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @author pengyangyan
 * @version 1.0.0
 * @date 2020年03月19日 16:38:00
 */
@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    TypeRepository typeRepository;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Type saveType(Type type) {
        return typeRepository.saveAndFlush(type);
    }

    @Override
    public Type getType(Long id) {
        Optional<Type> optional = typeRepository.findById(id);
        if (!optional.isPresent()){
            throw new NotFoundException("不存在该类型");
        }
        return optional.get();
    }

    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }

    @Override
    public List<Type> hotType(Integer size) {
        Pageable pageable = PageRequest.of(0,size);
        return typeRepository.findTop(pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Type updateType(Long id, Type type) {
        Optional<Type> optional = typeRepository.findById(id);
        if (!optional.isPresent()){
            throw new NotFoundException("不存在该类型");
        }
        Type t = optional.get();
        BeanUtils.copyProperties(type,t);
        return typeRepository.save(t);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeType(Long id) {
        typeRepository.deleteById(id);
    }

    @Override
    public Type findTypeByName(String name) {
        return typeRepository.findTypeByName(name);
    }
}
